package com.bawei.module_moto_circle.ui.post.adapter

import android.content.Context
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListUpdateCallback
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_common.dp
import com.bawei.lib_common.widget.nine_pic_grid.Image
import com.bawei.lib_image.GlideApp
import com.bawei.module_moto_circle.R
import com.bawei.module_moto_circle.databinding.ItemAfterSaleInfoBinding
import com.bawei.module_moto_circle.databinding.Layout1stClassCommentsItemBinding
import com.bawei.module_moto_circle.databinding.Layout2ndClassCommentsItemBinding
import com.bawei.module_moto_circle.databinding.LayoutCommentsFooterBinding
import com.bawei.module_moto_circle.databinding.LayoutCommentsHeaderBinding
import com.bawei.module_moto_circle.databinding.LayoutPostDetailsItemBinding
import com.bawei.module_moto_circle.databinding.LayoutPostItemBinding
import com.bawei.module_moto_circle.model.CommentInfo
import com.bawei.module_moto_circle.model.PostInfo
import com.bawei.module_moto_circle.model.Topic
import com.google.android.exoplayer2.util.MimeTypes

/**
 *作者：lxy
 *功能:
 *时间：2025/6/4
 */
class PostDetailsAdapter(
    private var comments: MutableList<CommentInfo> = mutableListOf(),
    private val onUserClick: ((String, Boolean) -> Unit)? = null,
    private val onImageClick: ((Int, Int, List<String>) -> Unit)? = null,
    private val clickShowAll: (CommentInfo, Int) -> Unit,
    //点击展开评论
    private val onClickLoadMore: (() -> Boolean)? = null,
    //失败重试
    private val onClickRetry: (() -> Unit)? = null,
    //长按删除
    private val onDeleteComment: ((commentId: String) -> Unit)? = null,
    //点赞留言
    private val onClickLike: ((postId: String, commentId: String, onPassed: (() -> Unit)?) -> Unit)? = null,
    private val onClickLikeView: ((postId: String, commentId: String, view: View, isLiked: Boolean, onPassed: (() -> Unit)?) -> Unit)? = null,
    private val onFollowClick: ((post: PostInfo) -> Unit)? = null,
    //导航
    private val onClickLocation: ((PostInfo) -> Unit)? = null,
    private val onClickMoreAfterSaleInfo: ((PostInfo) -> Unit)? = null,
    private val muber: Int = 2, private val isOnlyTpye: Boolean = false
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var post: PostInfo? = null
    private var afterSaleInfo: List<String>? = null
    var totalCommentsSize: Int = 0
    var m1stPageCommentsSize: Int = 0
    var haveAfterSaleInfo: Int = 0

    //评论列表前原始数据偏移 帖子详情+header
    private val mCommentOffsetInData
        get() =
            muber + haveAfterSaleInfo


    //默认 帖子+header+footer
    private val mDefaultCount
        get() = 3 + haveAfterSaleInfo


    enum class Type(val value: Int) {
        POST(1), COMMENTS_HEADER(2), FIRST_COMMENTS(3), SECOND_COMMENTS(4), COMMENTS_FOOTER(5), AFTER_SALE_INFO(
            6
        )
    }

    private lateinit var mContext: Context

    class CommentsDiffUtil(private val oldData: List<CommentInfo>, private val newData: List<CommentInfo>) : DiffUtil.Callback() {
        override fun getOldListSize(): Int {
            return oldData.size
        }

        override fun getNewListSize(): Int {
            return newData.size
        }

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldData[oldItemPosition].posts_comment_id == newData[newItemPosition].posts_comment_id
        }

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return (oldData[oldItemPosition].content == newData[newItemPosition].content &&
                    oldData[oldItemPosition].pinned == newData[newItemPosition].pinned &&
                    oldData[oldItemPosition].like_number == newData[newItemPosition].like_number)
        }

        override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
            return (oldData[oldItemPosition].content == newData[newItemPosition].content &&
                    oldData[oldItemPosition].pinned == newData[newItemPosition].pinned &&
                    oldData[oldItemPosition].is_like == newData[newItemPosition].is_like &&
                    oldData[oldItemPosition].like_number == newData[newItemPosition].like_number)
        }


    }


    override fun getItemViewType(position: Int): Int {
        if (haveAfterSaleInfo == 1) {
            return when (position) {
                0 -> Type.AFTER_SALE_INFO.value
                1 -> Type.POST.value
                2 -> Type.COMMENTS_HEADER.value
                in 2..comments.size + 2 -> {
                    return if (comments[position - mCommentOffsetInData].level==1) Type.FIRST_COMMENTS.value else Type.SECOND_COMMENTS.value
                }

                else -> Type.COMMENTS_FOOTER.value
            }
        } else {
            if (isOnlyTpye) {
                return when (position) {
                    0 -> Type.COMMENTS_HEADER.value
                    in 0..comments.size -> {
                        return if (comments[position - mCommentOffsetInData].level == 1) Type.FIRST_COMMENTS.value else Type.SECOND_COMMENTS.value
                    }

                    else -> Type.COMMENTS_FOOTER.value
                }
            } else {
                return when (position) {
                    0 -> Type.POST.value
                    1 -> Type.COMMENTS_HEADER.value
                    in 1..comments.size + 1 -> {
                        return if (comments[position - mCommentOffsetInData].level == 1) Type.FIRST_COMMENTS.value else Type.SECOND_COMMENTS.value
                    }

                    else -> Type.COMMENTS_FOOTER.value
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        mContext = parent.context
        when (viewType) {
            Type.AFTER_SALE_INFO.value -> {
                val binding: ItemAfterSaleInfoBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.item_after_sale_info,
                    parent,
                    false
                )
                return AfterSaleViewHolder(binding.root)
            }

            Type.POST.value -> {
                val binding: LayoutPostDetailsItemBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.layout_post_details_item,
                    parent,
                    false
                )
                val postDetailsViewModel =
                    PostDetailsViewHolder(binding.root, onImageClick, onUserClick, onFollowClick)
                binding.holder = postDetailsViewModel
                return postDetailsViewModel
            }

            Type.COMMENTS_HEADER.value -> {
                val binding: LayoutCommentsHeaderBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.layout_comments_header,
                    parent,
                    false
                )
                return CommentsHeaderViewHolder(binding.root)
            }

            Type.FIRST_COMMENTS.value -> {
                val binding: Layout1stClassCommentsItemBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.layout_1st_class_comments_item,
                    parent,
                    false
                )
                return FirstClassCommentsViewHolder(binding.root, onUserClick)
            }

            Type.SECOND_COMMENTS.value -> {
                val binding: Layout2ndClassCommentsItemBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.layout_2nd_class_comments_item,
                    parent,
                    false
                )
                return SecondCommentsViewHolder(binding.root)
            }

            else -> {
                val binding: LayoutCommentsFooterBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.layout_comments_footer,
                    parent,
                    false
                )
                return CommentsFooterViewHolder(
                    binding,
                    onClickLoadMore,
                    onClickRetry,
                    totalCommentsSize,
                    m1stPageCommentsSize
                )
            }
        }
    }

    override fun getItemCount(): Int {
        return comments.size + mDefaultCount
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (getItemViewType(position)) {
            Type.POST.value -> {
                val binding =
                    DataBindingUtil.getBinding<LayoutPostDetailsItemBinding>(holder.itemView)
                binding?.post = post
                post ?: return
                (holder as PostDetailsViewHolder).initView(post!!, position)
                binding?.nineGridView?.setPicsList(post?.image!!)
                binding?.nineGridView?.initView()
                binding?.lLocation?.setOnClickListener {
                    onClickLocation?.invoke(post!!)
                }

                binding?.lFollowState?.isSelected = post?.hasFollowed() ?: false
            }

            Type.COMMENTS_HEADER.value -> {
                val binding =
                    DataBindingUtil.getBinding<LayoutCommentsHeaderBinding>(holder.itemView)
                binding?.tvCommentsNum?.text = String.format("%d 条评论", totalCommentsSize)
            }
            Type.FIRST_COMMENTS.value -> {
                val binding = DataBindingUtil.getBinding<Layout1stClassCommentsItemBinding>(holder.itemView)
                binding?.let {
                    val comment = comments[position - mCommentOffsetInData]
                    it.comments = comment
                    it.viewHolder = holder as FirstClassCommentsViewHolder
                    //点击评论
                    it.root.setOnClickListener {
//                        val body = PostCommentBody().apply {
//                            this.postsId = comment.postsId
//                            this.parentId = comment.postsCommentId
//                            this.firstCommentId = comment.postsCommentId
//                            this.beReplyId = comment.createBy
//                        }
//                        onClickComments?.invoke(body, comment.requireCreateName())
                    }
                    if (comment.oneself) {
                        it.root.setOnLongClickListener {
                            onDeleteComment?.invoke(comment.posts_comment_id)
                            true
                        }
                    }
                    it.lLike.setOnClickListener {
//                        onClickLikeView?.invoke(comment.postsId, comment.postsCommentId, binding.ivLike, comment.isLike == 1) {
//                            val findComment = comments.find { t -> t.postsCommentId == comment.postsCommentId } ?: return@invoke
//                            val findPosition = comments.indexOf(findComment)
//                            handleClickLike(findComment)
//                            notifyItemChanged(findPosition + mCommentOffsetInData)
//                        }
//                        onClickLike?.invoke(comment.postsId, comment.postsCommentId) {
//                            val newPosition = comments.indexOf(comment)
//                            if (newPosition == -1) {
//                                return@invoke
//                            }
//                            val newComment = comments[newPosition]
//                            handleClickLike(newComment)
//                            notifyItemChanged(newPosition + mCommentOffsetInData)
//                        }
                    }
                }
            }

            Type.SECOND_COMMENTS.value -> {
                val binding = DataBindingUtil.getBinding<Layout2ndClassCommentsItemBinding>(holder.itemView)
                binding?.let {
                    val comment = comments[position - mCommentOffsetInData]
                    it.comments = comment
                    it.viewHolder = holder as SecondCommentsViewHolder
//                    it.root.setOnClickListener {
//                        val body = PostCommentBody().apply {
//                            this.postsId = comment.postsId
//                            this.parentId = comment.postsCommentId
//                            this.firstCommentId = comment.firstCommentId
//                            this.beReplyId = comment.createBy
//                        }
//                        onClickComments?.invoke(body, comment.requireCreateName())
//                    }
                    //圆角处理
                   // if (comments[position - mCommentOffsetInData].topRound) it.l2ndComments.setBackgroundResource(R.drawable.shape_bg_mask_round_top_4dp)
                    //if (comments[position - mCommentOffsetInData].bottomRound) it.l2ndComments.setBackgroundResource(R.drawable.shape_bg_mask_round_bottom_4dp)
                   // if (comments[position - mCommentOffsetInData].rect) it.l2ndComments.setBackgroundResource(R.drawable.shape_bg_mask_rect)
                    if (comment.oneself) {
                        it.root.setOnLongClickListener {
                            onDeleteComment?.invoke(comment.posts_comment_id)
                            true
                        }
                    }
                    it.lLike.setOnClickListener {

                        onClickLikeView?.invoke(comment.posts_id, comment.posts_comment_id, binding.ivLike, comment.is_like) {
                            val findComment = comments.find { t -> t.posts_comment_id == comment.posts_comment_id } ?: return@invoke
                            val findPosition = comments.indexOf(findComment)
                           // handleClickLike(findComment)
                            notifyItemChanged(findPosition + mCommentOffsetInData)
                        }
//                        onClickLike?.invoke(comment.postsId, comment.postsCommentId) {
//                            val newPosition = comments.indexOf(comment)
//                            if (newPosition == -1) {
//                                return@invoke
//                            }
//                            val newComment = comments[newPosition]
//                            handleClickLike(newComment)
//                            notifyItemChanged(newPosition + mCommentOffsetInData)
//                        }
                    }
                }
            }

            Type.COMMENTS_FOOTER.value -> {
                val binding =
                    DataBindingUtil.getBinding<LayoutCommentsFooterBinding>(holder.itemView)
                //重新设置评论数据
                (holder as CommentsFooterViewHolder).setCommentsSize(
                    totalCommentsSize,
                    m1stPageCommentsSize
                )
                binding?.viewHolder = holder
                //footer状态切换
                noMore = holder::noMore
                loading = holder::loading
                error = holder::error
            }
        }
    }

    private val callback = object : ListUpdateCallback {
        override fun onInserted(position: Int, count: Int) {
            this@PostDetailsAdapter.notifyItemRangeInserted(position + mCommentOffsetInData, count)
            this@PostDetailsAdapter.notifyItemChanged(position + mCommentOffsetInData - 1, count + 1)
        }

        override fun onRemoved(position: Int, count: Int) {
            this@PostDetailsAdapter.notifyItemRangeRemoved(position + mCommentOffsetInData, count)
        }

        override fun onMoved(fromPosition: Int, toPosition: Int) {
            this@PostDetailsAdapter.notifyItemMoved(fromPosition + mCommentOffsetInData, toPosition + mCommentOffsetInData)

        }

        override fun onChanged(position: Int, count: Int, payload: Any?) {
            this@PostDetailsAdapter.notifyItemRangeChanged(position + mCommentOffsetInData, count)
        }
    }
    fun setPostInfo(post: PostInfo?, totalSize: Int, _1stSize: Int) {
        this.post = post
        this.totalCommentsSize = totalSize
        this.m1stPageCommentsSize = _1stSize
        notifyItemRangeChanged(0, mCommentOffsetInData)
        notifyItemChanged(itemCount)
    }

    fun setCommentsNewData(newComments: MutableList<CommentInfo>){
        val ret = DiffUtil.calculateDiff(CommentsDiffUtil(comments, newComments), true)
        this.comments.clear()
        this.comments.addAll(newComments)
        notifyItemRangeChanged(0, mCommentOffsetInData)
        ret.dispatchUpdatesTo(callback)
    }


    //无更多数据
    var noMore: (() -> Unit)? = null

    //加载中
    var loading: (() -> Unit)? = null

    //加载错误
    var error: (() -> Unit)? = null

}

class PostDetailsViewHolder(
    itemView: View,
    private val onImageClick: ((Int, Int, List<String>) -> Unit)? = null,
    private val onUserClick: ((String, Boolean) -> Unit)? = null,
    private val onFollowClick: ((post: PostInfo) -> Unit)? = null,
) : RecyclerView.ViewHolder(itemView) {

    lateinit var postModel: PostInfo

    var isClickSpan: Boolean = false

    private val mBinding: LayoutPostDetailsItemBinding by lazy {
        DataBindingUtil.getBinding(this.itemView)!!
    }

    fun initView(post: PostInfo, position: Int) {
        mBinding.apply {
            handlePicOrVideo(post, position)
            postModel = post
            //处理帖子中携带的话题
            if (!post.topics.isNullOrEmpty())
                handlePostTopic(post, post.topics)
        }
    }

    private fun LayoutPostDetailsItemBinding.handlePicOrVideo(post: PostInfo, position: Int) {
        post.image ?: return
        if (post.image.size == 1 && MimeTypes.isVideo(post.image[0].contentType)) {
            //视频
            nineGridView.visibility = View.GONE
            lVideo.visibility = View.VISIBLE
            lVideo.setOnClickListener {
                // VideoPlayerActivity.jump(post.img[0].url)
            }
            val l = lVideo.layoutParams
            val video = post.image.firstOrNull() ?: return
            val videoHeight = video.imageHeight
            val videoWidth = video.imageWidth
            if (videoHeight > videoWidth) {
                l.width = 233.dp
                l.height = 311.dp
            } else {
                l.width = 343.dp
                l.height = 180.dp
            }
            lVideo.layoutParams = l
//            GlideApp.with(this.root).load(getAliOSSVideoImage(post.img[0].url)).applyRoundPic(4.dp, RoundedCornersTransformation.CornerType.ALL)
//                .into(ivVideo)
        } else {
            nineGridView.visibility = View.VISIBLE
            lVideo.visibility = View.GONE
            //图片
            nineGridView.setPicsList(post.image)
            onImageClick?.let {
//                nineGridView.setOnItemClickListener()

            }
            //nineGridView.initView(position)
        }

    }

    private fun handlePostTopic(
        post: PostInfo,
        topics: List<Topic>
    ) {
        val content = "post.requireContent()"
        val spannableStringBuilder = SpannableStringBuilder(content)
        //保存topic的起始位置
        val topicIndexMap = mutableMapOf<String, MutableList<Int>>()
        //保存topicId
        val topicIdMap = mutableMapOf<String, String>()
        //记录截取起始位置
        topics.forEach {
            //转换为#Topic#
            val topicName = String.format("#%s#", it.topicName)
            var temp = content
            var p = 0
            while (true) {
                val start = temp.indexOf(topicName)
                if (start > -1) {
                    if (topicIndexMap[topicName] == null) {
                        topicIndexMap[topicName] = mutableListOf()
                    }
                    topicIndexMap[topicName]!!.add(start + p)
                    topicIdMap[topicName] = it.topicId.toString()
                } else {
                    break
                }
                p += start + topicName.length
                temp = content.substring(p)
            }
        }
        //添加点击事件
        topicIndexMap.forEach { map ->
            map.value.forEach {
                //  spannableStringBuilder.setSpan(TopicSpan(map.key, ""), it, it + map.key.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                spannableStringBuilder.setSpan(
                    object : ClickableSpan() {
                        override fun onClick(p0: View) {
                            isClickSpan = true
                            (p0 as TextView).highlightColor = Color.TRANSPARENT
                            // TopicActivity.jump(topicIdMap[map.key] ?: "", map.key)
                        }

                        override fun updateDrawState(ds: TextPaint) {
                            ds.color = ContextCompat.getColor(
                                itemView.context,
                                com.bawei.lib_common.R.color.topic
                            )
                            ds.isUnderlineText = false
                        }
                    },
                    it, it + map.key.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
        mBinding.tvPostContent.movementMethod = LinkMovementMethod.getInstance()
        mBinding.tvPostContent.text = spannableStringBuilder

    }

    fun clickUser() {
        if (postModel.isOfficial()) return
        onUserClick?.invoke(postModel.create_by, postModel.isOfficial())
    }

    fun clickFollow() {
        onFollowClick?.invoke(postModel)
    }

}

class CommentsHeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

class AfterSaleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

class CannotCommentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

class CommentsFooterViewHolder(
    val binding: LayoutCommentsFooterBinding,
    private val onClickLoadMore: (() -> Boolean)? = null,
    private val onClickRetry: (() -> Unit)? = null,
    private var totalCommentSize: Int,
    private var m1stPageCommentsSize: Int
) :
    RecyclerView.ViewHolder(binding.root) {

    fun setCommentsSize(total: Int, m1stPageSize: Int) {
        this.totalCommentSize = total
        this.m1stPageCommentsSize = m1stPageSize
    }

    //是否显示
    fun show(): Boolean {
        val size = totalCommentSize - m1stPageCommentsSize
        return size > 0 && totalCommentSize > 10 && m1stPageCommentsSize >= 10
    }

    //format剩余评论数据
    fun formatRemainingCommentsNum(): String {
        val size = totalCommentSize - m1stPageCommentsSize
        return String.format("展开%d评论", size)
    }

    //点击加载更多
    fun loadMore() {
        if (onClickLoadMore?.invoke() != true)
            return
    }

    private fun retry(view: View) {
        onClickRetry?.invoke()
    }

    fun noMore() {
        binding.lLoad.visibility = View.VISIBLE
        binding.lLoadStatus.loadMoreLoadingView.visibility = View.GONE
        binding.lLoadStatus.loadMoreLoadEndView.visibility = View.VISIBLE
        binding.lLoadStatus.loadMoreLoadFailView.visibility = View.GONE
        binding.tv.visibility = View.GONE
    }

    fun loading() {
        binding.lLoad.visibility = View.VISIBLE
        binding.lLoadStatus.loadMoreLoadingView.visibility = View.VISIBLE
        binding.lLoadStatus.loadMoreLoadEndView.visibility = View.GONE
        binding.lLoadStatus.loadMoreLoadFailView.visibility = View.GONE
        binding.tv.visibility = View.GONE
    }

    fun error() {
        binding.lLoad.visibility = View.VISIBLE
        binding.lLoadStatus.loadMoreLoadingView.visibility = View.GONE
        binding.lLoadStatus.loadMoreLoadEndView.visibility = View.GONE
        binding.lLoadStatus.loadMoreLoadFailView.visibility = View.VISIBLE
        binding.tv.visibility = View.GONE
        binding.lLoadStatus.loadMoreLoadFailView.setOnClickListener(::retry)
    }

}

class FirstClassCommentsViewHolder(
    itemView: View,
    val onUserClick: ((String, Boolean) -> Unit)? = null
) : RecyclerView.ViewHolder(itemView) {
    val mBinding: Layout1stClassCommentsItemBinding by lazy {
        DataBindingUtil.getBinding(itemView)!!
    }

    fun clickUser() {
        if (mBinding.comments?.isOfficial() == true)
            return
        onUserClick?.invoke(mBinding.comments!!.create_by, false)
    }
}

class SecondCommentsViewHolder(
    itemView: View,
) :
    RecyclerView.ViewHolder(itemView) {
    val mBinding: Layout2ndClassCommentsItemBinding by lazy {
        DataBindingUtil.getBinding(itemView)!!
    }

    fun clickAllComments(comments: CommentInfo) {

    }

    //格式化回复评论内容 XXX回复：YY
    fun formatReplayContent(content: String, replyName: String?): CharSequence {
        val prefix = String.format("%s", replyName ?: "未知用户")
        val formatContent = String.format("回复%s：%s", prefix, content)
        val start = formatContent.indexOf(prefix)
        val end = start + prefix.length
        val spannableStringBuilder = SpannableStringBuilder(formatContent)
        spannableStringBuilder.setSpan(
            ForegroundColorSpan(ContextCompat.getColor(itemView.context, com.bawei.lib_common.R.color.color_919191)),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        return spannableStringBuilder
    }

    fun clickUser() {
        if (mBinding.comments?.isOfficial() == true)
            return
//        onUserClick?.invoke(mBinding.comments!!.create_by, false)
    }


}